<template>
    <div class="">
        <h4 class="margin_bottom20">会员列表</h4>
        

        <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="12">
                <el-button type="danger" size="small" @click="delGroup" icon="delete" :disabled="this.sels.length === 0">批量删除</el-button>
            </el-col>
            <el-col :span="6">
                <el-input placeholder="搜索..." size="small" v-model="searchKey">
                    <el-button slot="append" icon="search" @click="loadData"></el-button>
                </el-input>
            </el-col>
        </el-row>
        <template>
            <el-table :data="tableData" border style="width: 100%; text-align: center;margin-top:10px;" v-loading.body="loading"
                   @selection-change="selsChange" ref="table">
                <el-table-column type="selection" reserve-selection=""></el-table-column>  
                <el-table-column prop="id" header-align="center" label="id"></el-table-column>
                <el-table-column label="头像" header-align="center">
                    <template scope="scope">
                        <img :src="tableData[scope.$index].file" style="width:100px;"></img>
                    </template>
                </el-table-column>
                <el-table-column prop="username" label="用户名" header-align="center"></el-table-column>
                <el-table-column prop="sex" header-align="center" label="性别"></el-table-column>
                <el-table-column prop="phone" header-align="center" label="手机"></el-table-column>
                <el-table-column prop="email" header-align="center" label="邮箱"></el-table-column>
                <el-table-column prop="address" header-align="center" label="地址"></el-table-column>
                <el-table-column prop="created" header-align="center" label="创建日期"></el-table-column>
                <el-table-column prop="updated" header-align="center" label="更新日期"></el-table-column>
                <el-table-column prop="state" header-align="center" label="状态">
                    <template scope="scope">
                    <el-tag v-if="tableData[scope.$index].state == 1" type="success">已启用</el-tag>
                    <el-tag v-else type="danger">已停用</el-tag>
                </template>
                </el-table-column>
                    
                <el-table-column
                    label="操作"
                    width="120">
                    <template scope="scope">
                        <el-button v-if="tableData[scope.$index].state==1" @click="stop(tableData[scope.$index])" type="warning" size="mini">停用</el-button>
                        <el-button v-else @click="enable(tableData[scope.$index])" type="primary" size="mini">启用</el-button>
                        <el-button @click="deleted(tableData[scope.$index].id)" type="danger" size="mini">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[5,50,100,200]"
                :page-size="limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </template>
        
        <!-- 表单弹窗 -->
        <el-dialog title="修改会员" :visible.sync="dialogAddVisible" :show-close="false" before-close="beforeClose">

            <el-form :model="member"  ref="addForm">
                <el-form-item label="用户名" :label-width="formLabelWidth" prop="username"
                              :rules="[{ required: true, message: '用户名不能为空'}]">
                    <el-input v-model="member.username" auto-complete="off"></el-input>
                </el-form-item>

                <el-form-item label="性别" :label-width="formLabelWidth" prop="sex"
                    :rules="[{ required: true}]">
                     <el-radio v-model="radio" label="1">男</el-radio>
                     <el-radio v-model="radio" label="2">女</el-radio>
                     <el-radio v-model="radio" label="3">保密</el-radio>
                </el-form-item>

                <el-form-item label="手机" :label-width="formLabelWidth" prop="phone"
                              :rules="[{ required: true, message: '手机号不能为空'},
                              { type: 'number', message: '手机号必须为数字值'}]">
                    <el-input v-model.number="member.phone" auto-complete="off"></el-input>
                </el-form-item>

                <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email"
                              :rules="[{ required: true, message: '邮箱不能为空'},
                               { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur,change' }]">
                    <el-input v-model="member.email"></el-input>
                </el-form-item>   

                <!-- <el-form-item label="头像" :label-width="formLabelWidth" prop="file">
                    <el-upload class="avatar-uploader"
                        :action="uploadPath"
                        :show-file-list="false"
                        :on-success="setAvatar"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="member.file" :src="member" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item> -->
                <el-form-item label="备注" :label-width="formLabelWidth" prop="points">
                    <v-editor id="editor1" :input-content="inputContent" :upload-url="uploadURL" v-model="member.description"></v-editor>
                </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="reset('addForm')">重置</el-button>
                    <el-button @click="close('addFrom')">取消</el-button>
                    <el-button type="primary" @click="submit('addForm')">确 定</el-button>
                </div>
        </el-dialog>

    </div>
</template>
<script>

import Editor from '../../components/editor.vue'
    export default {
        data (){

            return {
                //时间选择
                value1: '',
                value2: '',

                status: '停用',
                radio: '1',
                tableData: [],
                sels: [],
                total: 0,  
                start: 0,  
                size: 10 ,
                currentPage: 1,
                total: 0,
                limit: 10,
                search: '',
                searchKey: '',
                loading: false,
                uploadPath: '',
                member: {
                    id: '',
                    username: '',
                    password: '',
                    phone: '',
                    email:'',
                    created:'',
                    updated:'',
                    sex: '',
                    address: '',
                    state: '',
                    file: '',
                    file:'',
                    description: '',
                    points: 0,
                    balance: '',
                    pass: '',
                    checkPass: '',
                },
                dialogAddVisible: false,
                dialogViewVisible: false,
                formLabelWidth: '120px',
                inputContent: '',
                uploadURL: ''//编辑器的上传图片地址
             }
            },
    
        
        methods : {
            //批量删除
            selsChange(sels) {  
                 this.sels = sels 
                },  
            delGroup(id) {
                var vm = this;
                //获取所有选中行的id组成的字符串，以逗号分隔  
                var ids = this.sels.map(member => member.id).join();
                this.$confirm('确定删除吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    
                    this.$http.delete(API.rootPath + "/members/" + ids).then((response) => {
                        if(response.body.status == 0) {

                            vm.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.$refs.table.clearSelection();
                            vm.loadData();
                            
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });                
            }, 
            handleCurrentChange(row, event, column) {  
                    this.$refs.table.toggleRowSelection(row)  
                }  ,

 
            //pageSize 改变时会触发,就是limit改变时候触发
            handleSizeChange(handleSizeChange) {
                this.limit = handleSizeChange;
                this.loadData();
            },

            //currentPage 改变时会触发
            handleCurrentChange(currentPage) {
                // console.log(currentPage);
                this.currentPage = currentPage;
                this.loadData();
            },
            loadData() {
                this.loading = true;
                this.$http.get(API.rootPath + "/members",
                 {params:{offset: this.limit*(this.currentPage - 1), 
                        limit: this.limit, 
                        searchKey: this.searchKey, 
                        companyId: localStorage.companyId}}).then((response) => {

                    this.tableData = response.body.data.rows;
                    this.total = response.body.data.total;
                    this.loading = false;
                }, (response) => {
                    // error callback
                });
            
            
             },
             searchData(){
                this.loading = true;
                this.$http.get(API.rootPath + "/members",
                 {params:{offset: this.limit*(this.currentPage - 1), 
                 limit: this.limit, 
                 search: this.search, 
                 companyId: localStorage.companyId}}).then((response) => {

                    this.tableData = response.body.data.rows;
                    this.total = response.body.data.total;
 
                    this.loading = false;
                }, (response) => {
                    // error callback
                });
            },
            add() {
                    
                this.initEntity();
                this.dialogAddVisible = true;
            },

            view(id) {
                var vm = this;
                //查询出指定id的商品，然后进入查看详情页面
                this.$http.get(API.rootPath + "/members/" + id).then((response) => {
                    //console.log(response.body);

                    if(response.body.status == 0) {
                        this.member = response.body.data;
                        this.inputContent = response.body.data.content;

                        vm.dialogViewVisible = true;
                    }
                });
            },
            deleted(id) {
                var vm = this;
                this.$confirm('确定删除吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete(API.rootPath + "/members/" + id).then((response) => {
                        if(response.body.status == 0) {

                            vm.$message({
                                message: '删除成功',
                                type: 'success'
                            });

                            vm.loadData();
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });                
            },
            setAvatar(res, file) {
                console.log("上传成功了", res);
                this.member.file = res;
            },
            beforeAvatarUpload(file) {
                // const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;
                // console.log("isJpg:", isJPG);
                // if (!isJPG) {
                //     this.$message.error('上传图片只能是 JPG 格式!');
                //     return;
                // }
                if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
                    return;
                }
                // return isJPG && isLt2M;
                return isLt2M;
            },
            submit(formName){

                var vm=this;

                //validate
                this.$refs.formName.validate((valid) => {
                    if (valid) {
                        var data = vm.member;

                        this.$axios.post(API.rootPath + "/members", data, {emulateJSON: false}).then((response) => {
                            //console.log(response.body);

                            if(response.data.status == 0) {
                                vm.$message({
                                    message: '保存成功',
                                    type: 'success'
                                });
                                vm.dialogAddVisible = false;
                                vm.dialogEditVisible = false;

                                this.loadData();
                            }
                        });
                    } else {
                        //console.log('error submit!!');
                        return false;
                    }
                });
            },
            edit(id) {
                var vm = this;
                //查询出指定id的member，然后进入修改页面
                this.$http.get(API.rootPath + "/members/" + id).then((response) => {
                    //console.log(response.body);

                    if(response.body.status == 0) {
                        this.member = response.body.data;
                        this.inputContent = response.body.data.content;

                        vm.dialogAddVisible = true;
                    }
                });
            },
            //停用
            stop(member) {
                
                member.state = 2;
                this.$axios.post(API.rootPath + "/members", member).then((response) =>{
                });
               
            },
            //启用
            enable(member) {
                member.state = 1;
                this.$axios.post(API.rootPath + "/members", member).then((response) =>{
                });
            },

            /**
             * 重置表单，并关闭
             */
            reset(formName) {
                this.$refs[formName].resetFields();
                // this.dialogAddVisible = false;
            },

            close(formName){
                this.dialogAddVisible = false;
            },

            /**
             * 关闭之前弹出确认
             */
            beforeClose(done) {
                var vm = this;

                this.$confirm('确认关闭？')
                    .then(_ => {
                        vm.reset('addForm');
                        done();
                    })
                    .catch(_ => {});
                
            },

            initEntity() {
                this.member = {
                    id: '',
                    username: '',
                    password: '',
                    phone: '',
                    email:'',
                    created:'',
                    updated:'',
                    sex: '',
                    address: '',
                    state: '',
                    file:'',
                    description: '',
                    points: 0,
                    balance: ''
                }
            }
        },
                //引入文本编辑器那个组件
        components: {
            'v-editor': Editor
        },
        created() {
            this.loadData();
            this.uploadPath = API.rootPath + "/rap/images/avatars/good";
            this.uploadURL = API.rootPath + "/rap/images/editors/good";
        }
    }
</script>
<style>
.el-dialog--small {
    width: 60%;
}
</style>
